﻿using EnvDTE;
using EnvDTE80;
using JoinBoxAlignPlug.修改文本;
using System;
using System.IO;
using System.Linq;
using System.Text;

namespace JoinBoxAlignPlug
{
    public class JoinBoxCommand
    {
        // 命令: 先执行vs自带的格式化,然后删除行尾空格,再进行等号和注释对齐
        public static void Execute(DTE2 vsDTE2, Document doc)
        {
            if (vsDTE2 == null)
                return;
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            //过滤规则
            var lst = new string[] { ".cs", ".cpp", "h" };
            var fileName = doc.FullName;
            var ex = Path.GetExtension(fileName).ToLower();
            if (!lst.Contains(ex))
                return;
            vsDTE2.ExecuteCommand("Edit.FormatDocument");
            new ReplaceTexts(doc);
        }

        public static void Execute(DTE2 vsDTE2)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            Execute(vsDTE2, vsDTE2.ActiveDocument);
        }
    }

    public class ReplaceTexts
    {
        public ReplaceTexts(Document doc)
        {
            if (doc == null)
                return;

            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            try
            {
                var objTD = (TextDocument)doc.Object();

                // 创建编辑点获取缓冲区所有文本,防止利用选择器造成滚动条改变
                var objEP = objTD.StartPoint.CreateEditPoint();
                var str1 = objEP.GetText(objTD.EndPoint);

                var cta = new ChangTextAlignment(str1, EncodingHelper.Read(doc.FullName)); //编码
                cta.TextTrimEnd();
                // cta.TextAlignment(","); 逗号对齐并不是一个好方案,尤其是与等号一起的
                cta.TextAlignment("=");
                cta.TextAlignment("//");

                //替换文本
                objEP.ReplaceText(objTD.EndPoint,
                    cta.ToString(),
                    (int)vsEPReplaceTextOptions.vsEPReplaceTextKeepMarkers);
            }
            catch
            { }
        }



    }
}
